package indi.kane.demandlist.controller;

import com.alibaba.fastjson.JSON;
import indi.kane.demandlist.entity.User;
import indi.kane.demandlist.service.impl.UserService;
import indi.kane.demandlist.vo.ResultVo;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName: UserController
 * @Author: kane
 * @Date: 2020-05-25 11:44 上午
 * @Description:
 */
@RequestMapping("user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("login")
    public ResultVo login(HttpServletResponse httpServletResponse,
                          @RequestBody User loginUser) {
        ResultVo resultVo = userService.login(loginUser.getName(), loginUser.getPassword());
        if (resultVo.getData() != null) {
            User users = (User) resultVo.getData();
            Cookie cookie = new Cookie("user", users.getId().toString());
            cookie.setPath("/");
            cookie.setMaxAge(600);
            httpServletResponse.addCookie(cookie);
        }
        return resultVo;
    }

    @PostMapping("isLogin")
    public ResultVo loginState(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();

        Integer id = 0;
        if (cookies == null) {
            return ResultVo.failed(ResultVo.NEEDLOGIN,"请先进行登录");
        }
        else {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("user")) {
                    id = cookie.getValue() == null
                            ? 0
                            : cookie.getValue() == "" ? 0 : Integer.valueOf(cookie.getValue());
                }
            }
            if (id.equals(0)) {
                return ResultVo.failed(ResultVo.NEEDLOGIN, "请先进行登录");
            }else {
                return userService.selectByPrimaryKey(id);
            }
        }
    }
}